package cn.juque.common.disruptor;

import cn.juque.common.base.DisruptorBody;
import cn.juque.common.base.DisruptorMessage;
import com.lmax.disruptor.RingBuffer;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;

/**
 * @author nuoka
 * @version 1.0.0
 * <li>IntelliJ IDEA</li>
 * <li></li>
 * @date 2021/8/24 23:54
 **/
@Slf4j
public class DisruptorHandler {

    @Resource
    private RingBuffer<DisruptorMessage<DisruptorBody>> disruptorRingBuffer;

    /**
     * 激活消费者
     * <li></li>
     * @param disruptorBody DisruptorBody
     */
    public void publish(DisruptorBody disruptorBody) {
        // 获取下一个事件插槽
        long sequence = this.disruptorRingBuffer.next();
        try {
            DisruptorMessage<DisruptorBody> messageBO = this.disruptorRingBuffer.get(sequence);
            messageBO.setBody(disruptorBody);
        } catch (Exception e) {
            log.error("disruptor get event error", e);
        }finally {
            this.disruptorRingBuffer.publish(sequence);
        }
    }
}
